/** 
 * File-Name:ArticleRepository.java
 *
 * Created on 2011-6-2 下午03:48:12
 * 
 * @author: Neo (neolimeng@gmail.com)
 * Software Engineering Institute, Peking University, China
 * 
 * Copyright (c) 2009, Peking University
 * 
 *
 */
package site.service;

import java.sql.Connection;
import java.util.ArrayList;
import java.util.List;

import neoutil.CommonEntity;
import neoutil.CommonService;
import neoutil.DaoSupport;
import neoutil.Page;

import org.apache.commons.dbutils.DbUtils;
import org.apache.log4j.Logger;

import site.dao.ArticleDao;
import site.dao.UserDao;
import site.entity.Article;
import site.entity.Role;
import site.entity.User;

/**
 * Description: 用户Article的各种存储相关操作。
 * 
 * @author: Neo (neolimeng@gmail.com) Software Engineering Institute, Peking
 *          University, China
 * @version 1.0 2011-6-2 下午03:48:12
 */
public class ArticleRepository extends CommonService {
	private static Logger log = Logger.getLogger(ArticleRepository.class);

	public String save(Article article) {
		Connection connection = null;
		try {
			connection = DaoSupport.getConnection();
			ArticleDao articleDao = new ArticleDao(connection);

			articleDao.save(article);
			return SUCCESS;
		} catch (Exception e) {
			log.error("保存Article对象出现异常！！");
			e.printStackTrace();
			return FAIL;
		} finally {
			closeConnection(connection);
		}
	}

	public String update(Article article) {
		Connection connection = null;
		try {
			connection = DaoSupport.getConnection();
			ArticleDao articleDao = new ArticleDao(connection);
			articleDao.update(article);
			return SUCCESS;
		} catch (Exception e) {
			e.printStackTrace();
			return FAIL;
		} finally {
			closeConnection(connection);
		}
	}

	public String updateVisitNum(Article article) {
		Connection connection = null;
		try {
			connection = DaoSupport.getConnection();
			ArticleDao articleDao = new ArticleDao(connection);

			String sql = "UPDATE article SET visitNum=? WHERE uuid=?";
			Object[] params = { article.getVisitNum() + 1, article.getUuid() };

			articleDao.execute(sql, params);
			return SUCCESS;
		} catch (Exception e) {
			e.printStackTrace();
			return FAIL;
		} finally {
			closeConnection(connection);
		}
	}

	public String deleteArticleByUuid(String uuid) {
		Connection connection = DaoSupport.getConnection();
		ArticleDao articleDao = new ArticleDao(connection);

		try {
			Object[] params = { uuid };
			articleDao.execute(
					"UPDATE article SET entityStatus=0 WHERE uuid=?", params);
			return SUCCESS;
		} catch (Exception e) {
			log.error("假删除Article对象出现异常！！");
			e.printStackTrace();
			return FAIL;
		} finally {
			try {
				DbUtils.close(connection);
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}
	}

	@Deprecated
	public Article get(long id) {
		Connection connection = null;

		try {
			connection = DaoSupport.getConnection();
			ArticleDao articleDao = new ArticleDao(connection);

			return articleDao.getById(id);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		} finally {
			closeConnection(connection);
		}
	}

	public Article get(String uuid) {
		Connection connection = null;

		try {
			connection = DaoSupport.getConnection();
			ArticleDao articleDao = new ArticleDao(connection);

			Article article = articleDao.getByUuid(uuid);
			UserDao userDao = new UserDao(connection);
			article.setAuthor(userDao.getById(article.getAuthorId()));

			return article;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		} finally {
			closeConnection(connection);
		}
	}

	public Page<Article> manageCheckedArticlesByCid(Page<Article> page,
			int cid, User user) {
		if (user == null) {
			return null;
		} else {
			Connection connection = null;
			try {
				connection = DaoSupport.getConnection();
				ArticleDao articleDao = new ArticleDao(connection);
				StringBuffer sql = new StringBuffer();
				sql.append("SELECT * FROM article WHERE cid=? AND entityStatus="
						+ CommonEntity.ENTITY_STATUS_NORMAL);
				if (user.getRid() != Role.ADMIN
						&& user.getRid() != Role.REVIEWER) {
					sql.append(" AND authorId=?");
				}
				sql.append(" ORDER BY updateDate DESC");

				Object[] params = null;
				if (user.getRid() != Role.ADMIN
						&& user.getRid() != Role.REVIEWER) {
					params = new Object[] { cid, user.getId() };
				} else {
					params = new Object[] { cid };
				}

				page = articleDao.find(page, sql.toString(), params);
				List<Article> tmp = new ArrayList<Article>();
				if (page.getResult() == null || page.getResult().size() == 0) {
					return null;
				} else {
					UserDao userDao = new UserDao(connection);
					for (Article a : page.getResult()) {
						a.setAuthor(userDao.getById(a.getAuthorId()));
						tmp.add(a);
					}
					page.setResult(tmp);
					return page;
				}
			} catch (Exception e) {
				e.printStackTrace();
				return null;
			} finally {
				closeConnection(connection);
			}
		}
	}

	/**
	 * Description:所有文章必须经过审查之后才能在页面上显示。
	 */
	public Page<Article> getCheckedArticlesByCid(Page<Article> page, int cid) {
		Connection connection = null;
		try {
			connection = DaoSupport.getConnection();
			ArticleDao articleDao = new ArticleDao(connection);
			String sql = "SELECT * FROM article WHERE cid=? AND status= "
					+ Article.STATUS_CHECKED_PASS + " AND entityStatus="
					+ CommonEntity.ENTITY_STATUS_NORMAL
					+ " ORDER BY updateDate DESC";
			Object[] params = { cid };
			page = articleDao.find(page, sql, params);
			List<Article> tmp = new ArrayList<Article>();
			if (page == null || page.getResult() == null || page.getResult().size() == 0) {
				return null;
			} else {
				UserDao userDao = new UserDao(connection);
				for (Article a : page.getResult()) {
					a.setAuthor(userDao.getById(a.getAuthorId()));
					tmp.add(a);
				}
				page.setResult(tmp);
				return page;
			}
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		} finally {
			closeConnection(connection);
		}
	}

	public Page<Article> getArticlesByCid(Page<Article> page, int cid) {
		Connection connection = null;
		try {
			connection = DaoSupport.getConnection();
			ArticleDao articleDao = new ArticleDao(connection);
			String sql = "SELECT * FROM article WHERE cid=? AND entityStatus="
					+ CommonEntity.ENTITY_STATUS_NORMAL
					+ " ORDER BY updateDate DESC";
			Object[] params = { cid };
			page = articleDao.find(page, sql, params);
			List<Article> tmp = new ArrayList<Article>();
			if (page.getResult() == null || page.getResult().size() == 0) {
				return null;
			} else {
				UserDao userDao = new UserDao(connection);
				for (Article a : page.getResult()) {
					a.setAuthor(userDao.getById(a.getAuthorId()));
					tmp.add(a);
				}
				page.setResult(tmp);
				return page;
			}
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		} finally {
			closeConnection(connection);
		}
	}

	public Page<Article> getUncheckedArticles(Page<Article> page) {
		Connection connection = null;
		try {
			connection = DaoSupport.getConnection();
			ArticleDao articleDao = new ArticleDao(connection);
			String sql = "SELECT * FROM article WHERE status= "
					+ Article.STATUS_UNCHECKED + " AND entityStatus="
					+ CommonEntity.ENTITY_STATUS_NORMAL
					+ " ORDER BY updateDate DESC";
			page = articleDao.find(page, sql);
			List<Article> tmp = new ArrayList<Article>();
			if (page.getResult() == null || page.getResult().size() == 0) {
				return null;
			} else {
				UserDao userDao = new UserDao(connection);
				for (Article a : page.getResult()) {
					a.setAuthor(userDao.getById(a.getAuthorId()));
					tmp.add(a);
				}
				page.setResult(tmp);
				return page;
			}
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		} finally {
			closeConnection(connection);
		}
	}

	public String checkArticle(String uuid, int status) {
		Connection connection = null;
		try {
			connection = DaoSupport.getConnection();
			ArticleDao articleDao = new ArticleDao(connection);
			String sql = "UPDATE article SET status = ? WHERE uuid=?";
			articleDao.execute(sql, new Object[] { status, uuid });

			return SUCCESS;
		} catch (Exception e) {
			e.printStackTrace();
			return EXCEPTION;
		} finally {
			closeConnection(connection);
		}
	}

	public Article getLatestArticleByCid(int cid) {
		Connection connection = null;

		try {
			connection = DaoSupport.getConnection();
			ArticleDao articleDao = new ArticleDao(connection);
			String sql = "SELECT * FROM article WHERE cid=? AND entityStatus=1 ORDER BY updateDate DESC";
			List<Article> articles = articleDao.find(sql, new Object[] { cid });

			if (articles == null || articles.size() == 0) {
				return null;
			} else {
				Article article = articles.get(0);

				UserDao userDao = new UserDao(connection);
				article.setAuthor(userDao.getById(article.getAuthorId()));

				return article;
			}
		} catch (Exception e) {
			log.error("按类别取得最新的Article，取得Article对象出现异常！！");
			e.printStackTrace();
			return null;
		} finally {
			try {
				DbUtils.close(connection);
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}
	}

	public Page<Article> search(Page<Article> page, String query) {
		Connection connection = DaoSupport.getConnection();
		ArticleDao articleDao = new ArticleDao(connection);

		try {
			Page<Article> articles = articleDao.find(page,
					"SELECT * FROM article WHERE entityStatus=1 and title like '%"
							+ query + "%'");
			return articles;
		} catch (Exception e) {
			log.error("搜索Article对象出现异常！！");
			e.printStackTrace();
			return null;
		} finally {
			try {
				DbUtils.close(connection);
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}
	}

	public List<Article> getLatestArticlesByCid(int cid, int topNum) {
		Connection connection = null;
		try {
			connection = DaoSupport.getConnection();
			ArticleDao articleDao = new ArticleDao(connection);

			String sql = "SELECT * FROM article WHERE cid=? AND entityStatus="
					+ CommonEntity.ENTITY_STATUS_NORMAL
					+ " ORDER BY updateDate DESC LIMIT 0,?";

			Object[] params = { cid, topNum };
			List<Article> articles = articleDao.find(sql, params);
			return articles;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		} finally {
			closeConnection(connection);
		}
	}

	public static void main(String[] args) {

	}

}
